package com.tjp.mall.auth.web;

import com.mysql.cj.util.StringUtils;
import com.tjp.common.exception.BizCodeEnum;
import com.tjp.common.utils.R;
import com.tjp.mall.auth.feign.MemberFeignService;
import com.tjp.mall.auth.feign.ThirdPartFeignService;
import com.tjp.mall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartFeignService thirdPartFeignService;

    @Autowired
    private MemberFeignService memberFeignService;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("login.html")
    public String login() {
        System.out.println("触发登录");
        return "login";
    }

    @GetMapping("register.html")
    public String register() {
        System.out.println("触发注册");
        return "register";
    }


    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendSmsCode(@RequestParam("phone") String phone) {
        //防止60秒内重新发送
        Object redisCode = redisTemplate.opsForValue().get(phone);
        if (redisCode != null) {
            String s = redisCode.toString();
            if (!"".equals(s)) {
                long l = Long.parseLong(s.split("_")[1]);
                if (System.currentTimeMillis() - l <= 60000) {
                    //说明验证码发送间隔不足一分钟
                    return R.error(BizCodeEnum.VALID_SMS_EXCEPTION.getCode(), BizCodeEnum.VALID_SMS_EXCEPTION.getMsg());
                }
            }
        }

        //生成随机验证码并将验证码存储到Redis服务中 key是手机 value为验证码
//        String code = String.valueOf((int)((Math.random()*9+1)*1000));
        String randomCode = "4426";
        String code = randomCode + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(phone, code,3, TimeUnit.MINUTES);
        System.out.println("生成随机验证码成功, 通过Feig调用远程thirdPartFeignService服务进行短信发送");
        thirdPartFeignService.getPhoneCode(phone, randomCode);
        return R.ok();
    }


    @PostMapping("/register")
    public String register(@Valid UserRegisterVo userRegisterVo, BindingResult result, Model model) {
        Map<String, String> map = new HashMap<>();

        //表示提交数据不合法
        if (result.hasErrors()) {
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field, defaultMessage);
            }
//            model.addAttribute("error", map);
            //添加返回错误信息
            this.addErrorMessage(model, map);
            return "register.html";
        }

        //表单提交的数据合法 校验验证码
        String code = (String) redisTemplate.opsForValue().get(userRegisterVo.getPhone());
        if (StringUtils.isNullOrEmpty(code)) {
            map.put("code", "请先获取验证码");
//            model.addAttribute("error", map);
            //添加返回错误信息
            this.addErrorMessage(model, map);
            return "register.html";
        }
        //进行校验
            code = code.split("_")[0];
        if (!code.equals(userRegisterVo.getCode())) {
            map.put("code", "验证码错误");
//            model.addAttribute("error", map);
            //添加返回错误信息
            this.addErrorMessage(model, map);
            return "register.html";
        }

        //验证码匹配 删除redis中的验证码
        redisTemplate.delete(userRegisterVo.getPhone());

        System.out.println("验证码---验证通过");
        System.out.println("通过Feign调用远程memberFeignService服务进行注册");
        R r = memberFeignService.registerUser(userRegisterVo);
        if (r.getCode() == 0) {
            System.out.println("调用远程注册接口成功, 注册成功");
            //注册成功
            return "redirect:http://localhost:8060/login.html";
        }else{
            //注册失败
            map.put("msg", r.getCode() + ":" + r.getMessage());
            //添加返回错误信息
            this.addErrorMessage(model, map);
//            model.addAttribute("error", map);
            return "register.html";
        }
//        return "redirect:/login.html";
    }

    private void addErrorMessage(Model model, Map<String, String> map) {
        model.addAttribute("error", map);
    }

}
